<script setup lang="ts">
import { router } from '@/router';
import { onUnmounted, ref, Ref, watch } from 'vue';
import { CodeContent } from '@/api/code/type';
import { saveCodeContent } from '@/api/code';
import { getSolveSuggestions } from '@/api/code/codeCompletion';
import MarkdownRenderer from './MarkdownRenderer.vue';
import { showToast } from 'vant';

const name = defineModel("name")
const codeContent = defineModel("codeContent") as Ref<CodeContent>;
const codeId = defineModel("codeId") as Ref<string>;
const termContent = defineModel("termContent") as Ref<string>;
const timeout = ref({} as NodeJS.Timeout);
const loading = ref(false);
const emit = defineEmits(["run"]);
const solveNotice = ref("### 欢迎使用SQL智能助手\n\n您可以在编辑器中编写SQL代码，执行后如遇到错误，我可以帮您分析和解决问题。\n\n**使用提示：**\n1. 编写SQL查询语句\n2. 点击运行按钮执行代码\n3. 如有错误，点击AI助手按钮获取帮助\n\n祝您编码愉快！");
const showPopup = ref(false);
const showText = ref('AI思考中...');
const isSaving = ref(false);

// 代码自动保存
watch(() => codeContent.value.content, () => {
    if (timeout.value) clearTimeout(timeout.value);
    timeout.value = setTimeout(() => {
        saveCodeWithStatus();
    }, 5000);
})

const saveCodeWithStatus = async () => {
    if (!codeId.value || isSaving.value) return;
    
    try {
        isSaving.value = true;
        codeContent.value.codeId = codeId.value;
        await saveCodeContent(codeContent.value);
        console.log('代码已自动保存');
    } catch (error) {
        console.error('自动保存失败', error);
    } finally {
        isSaving.value = false;
    }
}

const back = () => {
    router.back();
}

const run = () => {
    emit("run");
}

const save = async () => {
    try {
        isSaving.value = true;
        codeContent.value.codeId = codeId.value;
        await saveCodeContent(codeContent.value);
        showToast({
            message: '保存成功',
            position: 'top',
            icon: 'success',
        });
    } catch (error) {
        showToast({
            message: '保存失败，请重试',
            position: 'top',
            icon: 'cross',
        });
    } finally {
        isSaving.value = false;
    }
}

function getErrorLogText(text: string): string {
    // 正则表达式匹配以 ERROR 开头的段落
    const errorRegex = /^ERROR[\s\S]*?(?=\n{2,}|$)/gm;
    const errorParagraphs = text.match(errorRegex) || [];

    // 将段落用换行符拼接
    return errorParagraphs.join('\n');
}

const onClickCloseIcon = () => {
    showText.value = '';
}

const toSolve = async () => {
    showPopup.value = true;
    
    if (termContent.value.length !== 0 || codeContent.value.content.length !== 0) {
        const errorLog = getErrorLogText(termContent.value);
        const codeText = codeContent.value.content;
        loading.value = true;
        showText.value = '正在分析您的代码和错误信息...';
        
        try {
            let data = await getSolveSuggestions(codeText, errorLog);
            if (data.length === 0) {
                throw new Error(`解析错误！未获取到数据`);
            }
            showText.value = data.substring(3, data.length - 3);
        } catch (e) {
            showText.value = "### 很抱歉，分析出错\n\n我在处理您的请求时遇到了问题。请稍后再试或尝试以下操作：\n\n- 检查您的SQL语法\n- 确保您的代码已执行并产生错误信息\n- 尝试简化您的查询后再次请求帮助";
            console.error('AI分析错误:', e);
        } finally {
            loading.value = false;
        }
    } else {
        showText.value = solveNotice.value;
    }
}

onUnmounted(() => {
    clearTimeout(timeout.value);
})
</script>

<template>
    <div class="editor-toolbar">
        <!-- 左侧区域：返回和环境名称 -->
        <div class="toolbar-left">
            <button class="toolbar-btn" title="返回列表" @click="back">
                <van-icon name="arrow-left" />
            </button>
            <div class="environment-name" :title="name">{{ name || '未命名环境' }}</div>
            <span v-if="isSaving" class="save-indicator">
                <van-loading type="spinner" size="14px" />
                <span>保存中...</span>
            </span>
        </div>
        
        <!-- 右侧区域：操作按钮 -->
        <div class="toolbar-right">
            <button class="toolbar-btn primary" title="运行代码" @click="run">
                <van-icon name="play-circle-o" />
                <span>运行</span>
            </button>
            <button class="toolbar-btn" title="保存代码" @click="save">
                <van-icon name="save-o" />
                <span>保存</span>
            </button>
            <button 
                class="toolbar-btn ai-btn" 
                title="获取AI帮助" 
                @click="toSolve"
                :disabled="loading"
            >
                <van-icon name="bulb-o" />
                <span>AI助手</span>
                <van-loading v-if="loading" type="spinner" size="14px" class="ai-loading" />
            </button>
        </div>

        <!-- AI助手弹窗 -->
        <van-popup 
            v-model:show="showPopup" 
            closeable 
            round 
            @click-close-icon="onClickCloseIcon"
            class="ai-popup"
        >
            <div class="ai-popup-header">
                <van-icon name="bulb-o" class="ai-icon" />
                <h3>SQL智能助手</h3>
            </div>
            <div class="ai-popup-content">
                <van-loading v-if="loading" type="spinner" vertical>
                    正在分析代码...
                </van-loading>
                <MarkdownRenderer v-else :content="showText" />
            </div>
        </van-popup>
    </div>
</template>

<style lang="scss" scoped>
.editor-toolbar {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    
    .toolbar-left {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .environment-name {
            color: #e0e0e0;
            font-weight: 500;
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .save-indicator {
            display: flex;
            align-items: center;
            gap: 6px;
            color: rgba(224, 224, 224, 0.6);
            font-size: 12px;
        }
    }
    
    .toolbar-right {
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .toolbar-btn {
        display: flex;
        align-items: center;
        gap: 6px;
        height: 32px;
        padding: 0 12px;
        background: transparent;
        border: 1px solid rgba(255, 255, 255, 0.1);
        border-radius: 4px;
        color: #e0e0e0;
        cursor: pointer;
        transition: all 0.2s;
        
        &:hover {
            background: rgba(255, 255, 255, 0.05);
        }
        
        &:active {
            transform: translateY(1px);
        }
        
        &.primary {
            background: #1989fa;
            border-color: #1989fa;
            
            &:hover {
                background: #0076e4;
            }
        }
        
        &.ai-btn {
            background: #5cb85c;
            border-color: #4cae4c;
            position: relative;
            
            &:hover {
                background: #4cae4c;
            }
            
            .ai-loading {
                position: absolute;
                right: 8px;
                top: 50%;
                transform: translateY(-50%);
            }
        }
    }
}

.ai-popup {
    width: 92%;
    max-width: 700px;
    height: 500px;
    max-height: 80vh;
    display: flex;
    flex-direction: column;
    
    .ai-popup-header {
        display: flex;
        align-items: center;
        padding: 16px;
        border-bottom: 1px solid #f2f2f2;
        gap: 8px;
        
        .ai-icon {
            font-size: 20px;
            color: #5cb85c;
        }
        
        h3 {
            margin: 0;
            font-size: 18px;
            color: #333;
        }
    }
    
    .ai-popup-content {
        flex: 1;
        padding: 16px;
        overflow-y: auto;
        display: flex;
        justify-content: center;
    }
}
</style>